'Copyright (C) 2009 Christiaan Cable
'
'This program is free software; you can redistribute it and/or
'modify it under the terms of the GNU General Public License
'as published by the Free Software Foundation; either version 3
'of the License, or (at your option) any later version.
'
'This program is distributed in the hope that it will be useful,
'but WITHOUT ANY WARRANTY; without even the implied warranty of
'MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
'GNU General Public License for more details (LICENCE.TXT).

Imports System.Net
Imports System.Xml
Imports System.Windows.Forms

Public Class Adam
    Public ISPReturnData As New ISPReturnData
    Private CookieContainer As New System.Net.CookieContainer

    Public Sub New(ByVal ConfigurationData As ConfigurationData)
        Try
            'set rollover date
            SetRolloverDate(ConfigurationData, ISPReturnData)

            Dim strHTMLData As String

            'create credentials
            Dim cCache As New CredentialCache
            cCache.Add(New Uri("http://members.adam.com.au/um1.6/usage.xml"), "Basic", New NetworkCredential(ConfigurationData.Username, ConfigurationData.Password))

            'login, get xml
            strHTMLData = ISPGet("http://members.adam.com.au/um1.6/usage.xml", CookieContainer, cCache)
            'strHTMLData = My.Computer.FileSystem.ReadAllText("C:\programming\isp\adam\um1.4.xml", System.Text.Encoding.ASCII)

            If UA.DebugISP = True Then My.Computer.FileSystem.WriteAllText(GetAppDataPath() & "debug.htm", strHTMLData, False, System.Text.Encoding.ASCII)

            If strHTMLData.Contains("Your login attempt failed") = True Then
                ISPReturnData.ErrorMessage = "Login Failed"
                Exit Sub
            End If

            Dim doc As New XmlDocument
            doc.LoadXml(strHTMLData)

            ISPReturnData.PeakDownload = CSng(Val(GetElementsByTagName(doc, "MegabytesDownloadedTotal")))
            ISPReturnData.PeakUpload = CSng(Val(GetElementsByTagName(doc, "MegabytesUploadedTotal")))

            Dim ExternalDownload As Single = CSng(Val(GetElementsByTagName(doc, "MegabytesDownloadedExternal")))
            Dim LocalDownload As Single = ISPReturnData.PeakDownload - CSng(Val(GetElementsByTagName(doc, "MegabytesDownloadedExternal")))
            Dim NewsgroupDownload As Single = CSng(Val(GetElementsByTagName(doc, "MegabytesNewsgroupTotal")))
            Dim NewsgroupLimit As Integer = CInt(Val(GetElementsByTagName(doc, "NewsgroupQuota")))

            ISPReturnData.LastUpdated = CDate(GetElementsByTagName(doc, "LastUpdate"))
            'ISPReturnData.LastUpdated = Date.ParseExact(GetElementsByTagName(doc, "LastUpdate"), "yyyy-MM-ddTHH:mm:ss", Nothing)
            '2007-06-08T12:57:18+09:30

            '##########################################################

            ProcessISPData(ConfigurationData, ISPReturnData)

            'check for error
            If ISPReturnData.ErrorMessage <> "" Then Exit Sub

            'override calcs 
            If ISPReturnData.PeakDownload >= Val(ConfigurationData.PeakUsageLimit) Then
                ISPReturnData.ShapedNow = True
            End If

            If ISPReturnData.PeakUpload >= Val(ConfigurationData.PeakUsageLimit) Then
                ISPReturnData.ShapedNow = True
            End If

            If LocalDownload >= Val(ConfigurationData.PeakUsageLimit) Then
                ISPReturnData.ShapedNow = True
            End If

            '##########################################################

            'create graph data

            'external
            ISPReturnData.GraphItemList.Add(New GraphItem("External " & Format(System.Math.Floor((ExternalDownload / Val(ConfigurationData.PeakUsageLimit)) * 1000) / 10, "#0.0") & "% (" & ExternalDownload & " MB)", ExternalDownload, CSng(Val(ConfigurationData.PeakUsageLimit)), False))

            'local
            ISPReturnData.GraphItemList.Add(New GraphItem("Local " & Format(System.Math.Floor((LocalDownload / Val(ConfigurationData.PeakUsageLimit)) * 1000) / 10, "#0.0") & "% (" & LocalDownload & " MB)", LocalDownload, CSng(Val(ConfigurationData.PeakUsageLimit)), False))

            'uploads
            ISPReturnData.GraphItemList.Add(New GraphItem("Uploads " & Format(System.Math.Floor((ISPReturnData.PeakUpload / Val(ConfigurationData.PeakUsageLimit)) * 1000) / 10, "#0.0") & "% (" & ISPReturnData.PeakUpload & " MB)", ISPReturnData.PeakUpload, CSng(Val(ConfigurationData.PeakUsageLimit)), False))

            'newsgroups
            ISPReturnData.GraphItemList.Add(New GraphItem("Newsgroups " & Format(System.Math.Floor((NewsgroupDownload / NewsgroupLimit) * 1000) / 10, "#0.0") & "% (" & NewsgroupDownload & " MB)", NewsgroupDownload, NewsgroupLimit, False))

            'days elapsed
            ISPReturnData.GraphItemList.Add(New GraphItem("Days Elapsed " & Format((ISPReturnData.DaysUsed / (ISPReturnData.DaysUsed + ISPReturnData.DaysLeft)) * 100, "#0") & "% (" & ISPReturnData.DaysUsed & " Days)", ISPReturnData.DaysUsed, ISPReturnData.DaysUsed + ISPReturnData.DaysLeft, False))

            '##########################################################

            'create stats data
            'external
            'override default
            ISPReturnData.PeakUsageValue = (ExternalDownload / CSng(Val(ConfigurationData.PeakUsageLimit))) * 100
            ISPReturnData.PeakUsageRemainingDescription = (Val(ConfigurationData.PeakUsageLimit) - ExternalDownload).ToString & " MB"
            If ISPReturnData.DaysLeft > 0 Then
                ISPReturnData.PeakUsageRemainingPerDayDescription = (CInt((Val(ConfigurationData.PeakUsageLimit) - ExternalDownload) / ISPReturnData.DaysLeft)) & " MB/Day (" & ISPReturnData.DaysLeft & " Days)"
            Else
                ISPReturnData.PeakUsageRemainingPerDayDescription = (CInt((Val(ConfigurationData.PeakUsageLimit) - ExternalDownload))) & " MB/Day (" & ISPReturnData.DaysLeft & " Days)"
            End If

            ISPReturnData.TextItemList.Add(New TextItem("External Left :", ISPReturnData.PeakUsageRemainingDescription))
            ISPReturnData.TextItemList.Add(New TextItem("External Avg. Left :", ISPReturnData.PeakUsageRemainingPerDayDescription))

            'local
            ISPReturnData.TextItemList.Add(New TextItem("Local D/L Left :", (Val(ConfigurationData.PeakUsageLimit) - LocalDownload).ToString & " MB"))
            If ISPReturnData.DaysLeft > 0 Then
                ISPReturnData.TextItemList.Add(New TextItem("Local Avg. Left :", (CInt((Val(ConfigurationData.PeakUsageLimit) - LocalDownload) / ISPReturnData.DaysLeft)) & " MB/Day (" & ISPReturnData.DaysLeft & " Days)"))
            Else
                ISPReturnData.TextItemList.Add(New TextItem("Local Avg. Left :", (CInt((Val(ConfigurationData.PeakUsageLimit) - LocalDownload))) & " MB/Day (" & ISPReturnData.DaysLeft & " Days)"))
            End If

            'uploads
            ISPReturnData.TextItemList.Add(New TextItem("U/L Left :", (Val(ConfigurationData.PeakUsageLimit) - ISPReturnData.PeakUpload).ToString & " MB"))
            If ISPReturnData.DaysLeft > 0 Then
                ISPReturnData.TextItemList.Add(New TextItem("U/L Avg. Left :", (CInt((Val(ConfigurationData.PeakUsageLimit) - ISPReturnData.PeakUpload) / ISPReturnData.DaysLeft)) & " MB/Day (" & ISPReturnData.DaysLeft & " Days)"))
            Else
                ISPReturnData.TextItemList.Add(New TextItem("U/L Avg. Left :", (CInt((Val(ConfigurationData.PeakUsageLimit) - ISPReturnData.PeakUpload))) & " MB/Day (" & ISPReturnData.DaysLeft & " Days)"))
            End If

            If ISPReturnData.ShapedNow = False Then
                ISPReturnData.TextItemList.Add(New TextItem("Shaped :", "NO"))
            Else
                ISPReturnData.TextItemList.Add(New TextItem("Shaped :", "YES"))
            End If

            '##########################################################

            'process alerts
            If ConfigurationData.AlertEnable = True Then
                Dim Subject As String
                Dim Message As String
                Dim Count As Integer

                For Each strUsageValue As String In ConfigurationData.AlertValue.Items
                    Count += 1

                    'Alert1 = external
                    If Math.Floor(CInt(ISPReturnData.PeakUsageValue)) >= CInt(Val(strUsageValue)) Then
                        If ConfigurationData.Alert1Count < Count Then
                            ConfigurationData.Alert1Count += 1

                            'create image
                            CreateImageFile(ConfigurationData, ISPReturnData)

                            Subject = "You've used " & strUsageValue & " of your external data allowance."
                            Message = "You've reached " & strUsageValue & " of your maximum external data allowance for this month."
                            If ConfigurationData.AlertDialog = True Then
                                Dim NewfrmMessage As New frmMessage
                                NewfrmMessage.lblMessage.Text = Message
                                NewfrmMessage.Show()
                            End If
                            If ConfigurationData.AlertEmail = True Then SendMail(ConfigurationData.AlertMailServer, ConfigurationData.AlertMailTo, Subject, Message)
                        End If
                    End If

                    'Alert2 = local
                    If Math.Floor(CInt(System.Math.Floor((LocalDownload / Val(ConfigurationData.PeakUsageLimit)) * 1000) / 10)) >= CInt(Val(strUsageValue)) Then
                        If ConfigurationData.Alert2Count < Count Then
                            ConfigurationData.Alert2Count += 1

                            'create image
                            CreateImageFile(ConfigurationData, ISPReturnData)

                            Subject = "You've used " & strUsageValue & " of your local data allowance."
                            Message = "You've reached " & strUsageValue & " of your maximum local data allowance for this month."
                            If ConfigurationData.AlertDialog = True Then
                                Dim NewfrmMessage As New frmMessage
                                NewfrmMessage.lblMessage.Text = Message
                                NewfrmMessage.Show()
                            End If
                            If ConfigurationData.AlertEmail = True Then SendMail(ConfigurationData.AlertMailServer, ConfigurationData.AlertMailTo, Subject, Message)
                        End If
                    End If

                    'Alert3 = uploads
                    If Math.Floor(CInt(System.Math.Floor((ISPReturnData.PeakUpload / Val(ConfigurationData.PeakUsageLimit)) * 1000) / 10)) >= CInt(Val(strUsageValue)) Then
                        If ConfigurationData.Alert3Count < Count Then
                            ConfigurationData.Alert3Count += 1

                            'create image
                            CreateImageFile(ConfigurationData, ISPReturnData)

                            Subject = "You've used " & strUsageValue & " of your upload data allowance."
                            Message = "You've reached " & strUsageValue & " of your maximum upload data allowance for this month."
                            If ConfigurationData.AlertDialog = True Then
                                Dim NewfrmMessage As New frmMessage
                                NewfrmMessage.lblMessage.Text = Message
                                NewfrmMessage.Show()
                            End If
                            If ConfigurationData.AlertEmail = True Then SendMail(ConfigurationData.AlertMailServer, ConfigurationData.AlertMailTo, Subject, Message)
                        End If
                    End If

                    'Alert4 = newsgroups
                    If Math.Floor(CInt(System.Math.Floor((NewsgroupDownload / NewsgroupLimit) * 1000) / 10)) >= CInt(Val(strUsageValue)) Then
                        If ConfigurationData.Alert4Count < Count Then
                            ConfigurationData.Alert4Count += 1

                            'create image
                            CreateImageFile(ConfigurationData, ISPReturnData)

                            Subject = "You've used " & strUsageValue & " of your newsgroups data allowance."
                            Message = "You've reached " & strUsageValue & " of your maximum newsgroups data allowance for this month."
                            If ConfigurationData.AlertDialog = True Then
                                Dim NewfrmMessage As New frmMessage
                                NewfrmMessage.lblMessage.Text = Message
                                NewfrmMessage.Show()
                            End If
                            If ConfigurationData.AlertEmail = True Then SendMail(ConfigurationData.AlertMailServer, ConfigurationData.AlertMailTo, Subject, Message)
                        End If
                    End If
                Next
            End If

        Catch ex As Exception
            ISPReturnData.ErrorMessage = ex.Message
        End Try

    End Sub

End Class